﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.Resolution;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Blueprints.Defaults
{
    /// <summary>
    /// Describes a collection.
    /// </summary>
    internal sealed class DefaultCollectionDescriptor : ICollectionDescriptor
    {
        private readonly MethodInfo addMethod;

        /// <summary>
        /// Creates a new DefaultCollectionDescriptor.
        /// </summary>
        /// <param name="type">The type of collection.</param>
        public DefaultCollectionDescriptor(Type type)
        {
            Type = type;
            Type elementType;
            if (!TryGetAddMethod(type, out addMethod, out elementType))
            {
                throw new InvalidOperationException("Type '" + type.Name + "' is not a collection type: No suitable Add method found.");
            }

            ElementType = elementType;
        }

        /// <summary>
        /// Gets the type of collection.
        /// </summary>
        public Type Type
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the type of elements in the collection.
        /// </summary>
        public Type ElementType
        {
            get;
            private set;
        }

        /// <summary>
        /// Creates a new collection.
        /// </summary>
        /// <returns>The created collection.</returns>
        public object CreateInstance()
        {
            return (IEnumerable)Activator.CreateInstance(Type);
        }

        /// <summary>
        /// Adds an element to the collection.
        /// </summary>
        /// <param name="collection">The collection to add <paramref name="element"/> to.</param>
        /// <param name="element">The element to add.</param>
        public void Add(object collection, object element)
        {
            addMethod.Invoke(collection, new object[] { element });
        }

        /// <summary>
        /// Gets the elements of <paramref name="collection"/>.
        /// </summary>
        /// <param name="collection">The collection of which to get the elements.</param>
        /// <returns>The elements of the collection.</returns>
        public IEnumerable GetElements(object collection)
        {
            return (IEnumerable)collection;
        }

        internal static bool TryGetAddMethod(Type type, out MethodInfo addMethod, out Type elementType)
        {
            foreach (MethodInfo candidate in GetAllMethods(type))
            {
                if (!candidate.Name.Equals("Add", StringComparison.Ordinal))
                {
                    continue;
                }

                if (!candidate.IsPublic)
                {
                    continue;
                }

                if (candidate.IsStatic)
                {
                    continue;
                }

                ParameterInfo[] parameters = candidate.GetParameters();
                if (parameters.Length != 1)
                {
                    continue;
                }

                elementType = parameters[0].ParameterType;
                addMethod = candidate;
                return true;
            }

            elementType = default(Type);
            addMethod = default(MethodInfo);
            return false;
        }

        private static IEnumerable<MethodInfo> GetAllMethods(Type type)
        {
            foreach (MethodInfo method in type.GetRuntimeMethods())
            {
                yield return method;
            }

            TypeInfo typeInfo = type.GetTypeInfo();
            foreach (Type interfaceType in typeInfo.ImplementedInterfaces)
            {
                foreach (MethodInfo method in GetAllMethods(interfaceType))
                {
                    yield return method;
                }
            }
        }
    }
}